//工具类js
//防抖
function debounce(fn,wait,immediate){
    if(typeof fn !== 'function'){
      alert('fn参数必须是函数')
    }
    if(typeof wait !=='number'){
      alert('输入必须是数字')
    }
    if(typeof immediate !=='boolean'){
      alert('输入必须是布尔值')
    }
      let timeout 
      return function proxy(){
        if(timeout){
          clearTimeout(timeout)
        }
        if(immediate){
          let timeNow = !timeout   //!undefine !1
          timeout  = setTimeout(function(){
            timeout =null;
          },wait)
          console.log(timeNow)
          if(timeNow){
            fn.apply(this,arguments)
          }
        }else{
          timeout = setTimeout(()=>{
          //es6的箭头函数本身没有this this怎么判断  看定义的作用域
          //作用域是proxy 所以这里的this指向proxy
          // call apply bind
              fn.apply(this,arguments)
         },wait)
        }
         
      }
  }

  //节流
  function torottled(fn,delay){
    //在节流函数中触发事件处理函数
     let timer = null;
     let startTime = Date.now();
     //页面刷新后立刻获取
     return function proxy(){
         clearTimeout(timer)
         //滚动触发事件
         let curTime = Date.now()//触发事件时间戳 curTime一定是比startTime更大
         let remaining = delay - (curTime-startTime);
         if(remaining<0){
             //说明事件处理海曙可以出触发了
             fn()
             startTime = Date.now();
         }else{
             timer = setTimeout(fn,remaining);
             console.log(timer);
         }

 }
}
//过期storage
let myStorage = {
    set(key,value,time){
        if(!time){
          time=60;
        }
     let endTime = new Date().getTime()+time*60*1000;
     localStorage.setItem(key,JSON.stringify({
        data:value,
        time:endTime
     }))
    },
    get(key){
     if(!localStorage.getItem(key)){
        return null;
     }
     let result = JSON.parse(localStorage.getItem(key))
     let nowTime = new Date().getTime()
     if(nowTime>result.time){
        this.remove(key)
        return null;
     }
     return result.data;
    },
    remove(key){
     localStorage.removeItem(key)
    }
}

//promise+ajax
function myAjax(url,method,data,token){
    let promise = new Promise((resolve,reject) => {
        let xhr = new XMLHttpRequest()
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                if((xhr.status >= 200 && xhr.status < 300)||xhr.status === 304){
                    resolve(JSON.parse( xhr.response))
                }else{
                    reject(new Error("error"))
                }
            }
        }
        if(method.toUpperCase() === "GET"){
           let paramslist = [];
           for(key in data){
               paramslist.push(key + "=" + data[key])
           }
           //根据get请求方法对url进行拼接
           let params = paramslist.join("&");
           url = url + "?" + params;
         
           xhr.open("get",url);
           //使用get请求将内容连接在url后面
           if(token){
            xhr.setRequestHeader('x-token',token)
           }

          // xhr.headers.token = token
           xhr.send()

        }
        if(method.toUpperCase() === "POST"){
            xhr.open("post", url);
            xhr.setRequestHeader("Content-Type", "application/json");
            // xhr.setRequestHeader('x-token',token)
            if(token){
            xhr.setRequestHeader('x-token',token)
           }
            xhr.send(JSON.stringify(data));
            //使用post请求时将内容放在send里面
        }

    })
    return promise
}
export default {
    debounce,
    torottled,
    myStorage,
    myAjax,
}